import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../src/store/index' // 引入vuex
import { getMenu } from '../src/api/http'

const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace

// 此处逻辑是处理，通过this.$router.push()或this.$router.replce()方法跳转同一个路由页面报错问题
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    // 如果指定了成功或者失败的回调
    if (onResolve || onReject) {
        return originalPush.call(this, location, onResolve, onReject)
    }
    // 没有指定成功或者失败的回调，要用catch处理
    return originalPush.call(this, location).catch((err) => {
        // 如果是重复导航产生的错误，不再向外传递错误
        if (VueRouter.isNavigationFailure(err)) {
            return err
        }
        // 如果不是重复导航的错误，将错误向下传递
        return Promise.reject(err)
    })
}

VueRouter.prototype.replace = function (location, onResolve, onReject) {
    if (onResolve || onReject) {
        return originalReplace.call(this, location, onResolve, onReject)
    }
    return originalReplace.call(this, location).catch((err) => {
        if (VueRouter.isNavigationFailure(err)) {
            return err
        }
        return Promise.reject(err)
    })
}


Vue.use(VueRouter)

const routes = [
	{
		path: '/login',
		name: 'login',
		component: () => import('../src/views/login/index.vue')
	},
	{
		path: '/',
		name: 'main',
		redirect: 'home',
		component: () => import('../src/views/Main.vue'),
		children: [
			// {
			// 	path: 'home',
			// 	name: 'home',
			// 	component: () => import('../src/views/home/index.vue')
			// }
			// {
			// 	path: 'mall',
			// 	name: 'mall',
			// 	component: () => import('../src/views/mall/index.vue')
			// },
			// {
			// 	path: 'user',
			// 	name: 'user',
			// 	component: () => import('../src/views/user/index.vue')
			// },
			// {
			// 	path: 'other/pageOne',
			// 	name: 'otherOne',
			// 	component: () => import('../src/views/others/PageOne.vue')
			// },
			// {
			// 	path: 'other/pageTwo',
			// 	name: 'otherTwo',
			// 	component: () => import('../src/views/others/PageTwo.vue')
			// },
			// {
			// 	path: 'other/xj/pageThree',
			// 	name: 'otherThree',
			// 	component: () => import('../src/views/others/xj/PageThree.vue')
			// }
		]
	}
]

const router = new VueRouter({
	routes
})

router.beforeEach(async(to, from, next) => {
	if (to.name != 'login') {
		let token = localStorage.getItem('token');
		if (token) {
			if (store.state.pannel.menus.length === 0) {
				let { data } = await getMenu();
				console.log(to);
				store.commit('pannel/initMenus', { menus: data.menus, path: to.path });
				let menuRoutes = store.getters['pannel/menuRoutes'];
				menuRoutes.forEach((item) => {
					item.component = () => import(`../src/views/${item.url}`); 
					router.addRoute('main', item);
				});
				next({...to, replace: true });
			} else {
				next();
			}
		} else {
			next({ name: 'login' })
		}
	} else { 
		next()
	}
})

export default router

